from django.conf import settings
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from tablestore import OTSClient, PK_AUTO_INCR, TableMeta, TableOptions, ReservedThroughput, CapacityUnit


class TableAPIView(APIView):
    @property
    def client(self):
        return OTSClient(settings.OTS_ENDPOINT, settings.OTS_ID, settings.OTS_SECRET, settings.OTS_INSTANCE)
    def post(self,request):
        """创建表"""
        # 设置主键和字段
        table_name = "user_message_table"

        # schema_of_primary_key = [
        # ('字段名', '字段类型', PK_AUTO_INCR),
        # ('uid', 'STRING')
        # ]
        # 主键列
        schema_of_primary_key = [
            ('user_id', 'INTEGER'),
            ('sequence_id', 'INTEGER',PK_AUTO_INCR),
            ("sender_id",'INTEGER'),
            ("message_id",'INTEGER')
        ]
        # 设置表的元信息
        table_meta = TableMeta(table_name, schema_of_primary_key)
        # 设置数据的有效期
        table_option = TableOptions(7*86400, 5)
        # 设置数据的预留读写吞吐量
        reserved_throughput = ReservedThroughput(CapacityUnit(0, 0))
        # 创建数据
        self.client.create_table(table_meta, table_option, reserved_throughput)

        return Response({"message":"ok"})

    def delete(self, request):
        """删除表"""
        table = "user_message_table"
        self.client.delete_table(table)
        return Response({"message": "ok"})

    def get(self, request):
        """列出所有的表"""
        table_list = self.client.list_table()
        for table in table_list:
            print(table)

        return Response({"message": "ok"})

